/**
 *
 */
package com.perceptivesoftware.licensing.server.util;

import java.io.File;
import java.util.Properties;
import java.util.regex.Pattern;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.perceptivesoftware.licensing.client.common.exceptions.FileException;
import com.perceptivesoftware.licensing.server.handler.PropertiesHandler;

/**
 * 
 * <p/>
 * Copyright 2012 Perceptive Software
 * <p/>
 * Project: Perceptive Licensing
 * 
 * @author Laurie Katz
 * 
 */
public class ServerUtils {
	public static final String semiColonRegex = Pattern.quote(";");

	private static final Properties props = new PropertiesHandler().getProperties(Constants.APPLICATION_PROPERTIES);

	public static void ensureParentFolderExists(final File tempFile)
			throws FileException {
		final File parent = new File(tempFile.getParent());
		if (!parent.exists()) {
			if (!parent.mkdirs()) {
				throw new FileException("Unable to make directory: "
						+ parent.getAbsolutePath());
			}
		}
	}

	public static String getSpringSecurityUsername() {
		String principalName = null;
		final SecurityContext sc = SecurityContextHolder.getContext();

		final Authentication auth = sc.getAuthentication();

		if (auth.getPrincipal() instanceof UserDetails) {
			final UserDetails ud = (UserDetails) auth.getPrincipal();
			principalName = ud.getUsername();
		} else if (auth.getPrincipal() instanceof String) {
			principalName = (String) auth.getPrincipal();
		} else {
			throw new RuntimeException("Invalid Security config.");
		}
		return principalName;
	}

	public static String property(String propKey, String defaultVal) {
		try {
			return property(propKey);
		} catch (final MissingParameterException e) {
			return defaultVal;
		}
	}

	public static String property(String propKey) {
		final String prop = ServerUtils.getStringProperty(propKey);
		if (prop == null) {
			throw new MissingParameterException("ERROR: Missing Property: "
					+ propKey);
		}
		return prop;
	}

	public static String getStringProperty(String property) {
		return props.getProperty(property, null);
	}
}
